package com.jianbing.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.Customer;
import com.jianbing.entity.Result;
import com.jianbing.util.AkasCreate;
import com.jianbing.util.Des;
import com.jianbing.util.StringUtils;
import com.jianbing.util.TableUtil;
import com.mongodb.BasicDBObject;

/**
 * 
 * 客戶controller
 * 
 * @author cwl
 * @date 2017年5月12日
 *
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
	Logger logger = Logger.getLogger(CustomerController.class);

	@Value("#{propertiesReader['keysalt']}")
	private String keysalt;

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result addCustomer(HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute Customer customer) {
		Result result = new Result();
		ModelMap model = new ModelMap();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		customer.setCreateDate(dateFormat.format(new Date()));
		if (StringUtils.isEmpty(customer.getCompanyName()) || StringUtils.isEmpty(customer.getCompanyEmail())
				|| StringUtils.isEmpty(customer.getPassword())) {
			result.setCode(-1);
			result.setMsg("参数错误");
			return result;
		}
		try {
			BasicDBObject queryObject = new BasicDBObject();
			queryObject.append("companyEmail", customer.getCompanyEmail());
			Customer existCustomer = MongoDBDao.findOne(TableUtil.customer, Customer.class, queryObject);
			if (existCustomer != null) {
				result.setCode(-1);
				result.setMsg("用户已存在");
				return result;
			}
			if (StringUtils.isNotEmpty(customer.getPassword())) {
				customer.setPassword(Des.encrypt(customer.getPassword(), keysalt));
			}
			customer = AkasCreate.create(customer);
			MongoDBDao.insert(TableUtil.customer, customer);
			model.addAttribute("customer", customer);
			result.setData(model);
			result.setMsg("success");
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(-1);
			result.setMsg("系统异常");
			return result;
		}
	}

	@RequestMapping(value = "/query")
	public @ResponseBody Result queryCustomer(HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute Customer customer) {
		Result result = new Result();
		ModelMap model = new ModelMap();
		Map<String, String> map = new HashMap<String, String>();
		if (!StringUtils.isEmpty(customer.getAppKey())) {
			map.put("appKey", customer.getAppKey());
		}
		if (!StringUtils.isEmpty(customer.getCompanyName())) {
			map.put("companyName", customer.getCompanyName());
		}

		if (!StringUtils.isEmpty(customer.getCompanyNumber())) {
			map.put("companyNumber", customer.getCompanyNumber());
		}
		if (!StringUtils.isEmpty(customer.getCompanyEmail())) {
			map.put("companyEmail", customer.getCompanyEmail());
		}
		try {
			List<Customer> list = MongoDBDao.queryForList(TableUtil.customer, map, Customer.class);
			model.addAttribute("customerList", list);
			result.setData(model);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(-1);
			result.setMsg("系统异常");
		}
		return result;
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result updateCustomer(HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute Customer customer) {
		Result result = new Result();
		if (StringUtils.isEmpty(customer.getAppKey())) {
			result.setCode(-1);
			result.setMsg("参数错误");
			return result;
		}
		try {
			BasicDBObject queryObject = new BasicDBObject();
			queryObject.append("appKey", customer.getAppKey());
			Customer oldCustomer = MongoDBDao.findOne(TableUtil.customer, Customer.class, queryObject);
			if (oldCustomer != null) {
				if (!StringUtils.isEmpty(customer.getCallBackUrl())) {
					oldCustomer.setCallBackUrl(customer.getCallBackUrl());
				}
				if (!StringUtils.isEmpty(customer.getCompanyName())) {
					oldCustomer.setCompanyName(customer.getCompanyName());
				}
				if (!StringUtils.isEmpty(customer.getCompanyNumber())) {
					oldCustomer.setCompanyNumber(customer.getCompanyNumber());
				}
				if (!StringUtils.isEmpty(customer.getCompanyEmail())) {
					oldCustomer.setCompanyEmail(customer.getCompanyEmail());
				}
				if (!StringUtils.isEmpty(customer.getCreateDate())) {
					oldCustomer.setCreateDate(customer.getCreateDate());
				}
				if (!StringUtils.isEmpty(customer.getPassword())) {
					oldCustomer.setPassword(Des.encrypt(customer.getPassword(), keysalt));
				}
			}
			long count = MongoDBDao.update(TableUtil.customer, queryObject, oldCustomer);
			if (count <= 0) {
				result.setCode(-1);
				result.setMsg("更新失败");
				return result;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(-1);
			result.setMsg("系统异常");
		}
		return result;
	}

}
